package slxy.jiangtao.dts.controller.user;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import slxy.jiangtao.dts.core.common.bean.Constants;
import slxy.jiangtao.dts.core.common.bean.FormCriteria;
import slxy.jiangtao.dts.core.common.bean.FormQuery;
import slxy.jiangtao.dts.core.common.bean.JSONResult;
import slxy.jiangtao.dts.core.common.hibernate.qbc.Page;
import slxy.jiangtao.dts.core.common.service.CommonService;
import slxy.jiangtao.dts.core.util.StringUtil;
import slxy.jiangtao.dts.entity.sys.*;
import slxy.jiangtao.dts.service.sys.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by JiangTao on 2017/1/14.
 */
@Controller
@RequestMapping("user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private CommonService commonService;
    @Autowired
    private UserService userService;


    /**
     * 社员列表
     */
    @RequestMapping(value = "userList")
    public String userListGet(ModelMap modelMap) {
        /**部门列表*/
        List<Depart> departList = commonService.getList(Depart.class);
        FormQuery formQuery = new FormQuery("sys.User");

        ArrayList<FormCriteria> formCriterias = new ArrayList<>();
        //默认只显示在职人员
        formCriterias.add(new FormCriteria("statu", "eq", Constants.STATU_FLAG_NORMAL));

        formQuery.setCriterias(formCriterias);
        Page page = commonService.getPage(formQuery);
        modelMap.addAttribute("departlist", JSON.toJSONString(departList));
        modelMap.addAttribute("page", JSON.toJSONString(page));
        return "user/userlist";
    }

    /**
     * 用户基本信息跳转页面
     */
    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public String detailGet(ModelMap modelMap, @RequestParam Integer id) {
        User user = commonService.get(User.class, id);
        modelMap.addAttribute("user", user);
        modelMap.addAttribute("college", user.getCollegeId() != null ? commonService.get(College.class, user.getCollegeId()).getName() : "");
        modelMap.addAttribute("major", user.getMajorId() != null ? commonService.get(Major.class, user.getMajorId()).getName() : "");
        modelMap.addAttribute("depart", user.getDepartId() != null ? commonService.get(Depart.class, user.getDepartId()).getName() : "");
        return "user/detail";
    }

    /**
     * 添加用户跳转页面
     */
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String addGet(ModelMap modelMap) {
        modelMap.addAttribute("roleList", JSON.toJSONString(commonService.getList(Role.class)));
        modelMap.addAttribute("departList", JSON.toJSONString(commonService.getList(Depart.class)));
        return "user/add";
    }

    /**
     * 添加用户提交页面
     */
    @RequestMapping(value = "addSubmit", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult addPost(User user, HttpServletRequest request) {
        int re = userService.insert(user);
        return re > 0 ? JSONResult.success("添加成功") : JSONResult.failure("添加失败");
    }

    /**
     * 社员学号验证
     */
    @RequestMapping("noCheck")
    @ResponseBody
    public JSONResult noCheck(String no) {
        User user = commonService.findUniqueByProperty(User.class, "no", no);
        if (user == null) {
            return JSONResult.success("该学号不存在");
        } else {
            return JSONResult.failure("该学号已存在");
        }
    }

    /**
     * 管理员编辑用户页面跳转
     */
    @RequestMapping(value = "update", method = RequestMethod.GET)
    public String updateGet(ModelMap modelMap, @RequestParam Integer id) {
        if (id != null) {
            modelMap.addAttribute("user", commonService.get(User.class, id));
        }
        modelMap.put("roleList", JSON.toJSONString(commonService.getList(Role.class)));
        modelMap.put("collegeList", JSON.toJSONString(commonService.getList(College.class)));
        modelMap.put("majorList", JSON.toJSONString(commonService.getList(Major.class)));
        modelMap.put("departList", JSON.toJSONString(commonService.getList(Depart.class)));
        return "user/update";
    }

    /**
     * 编辑用户提交
     */
    @RequestMapping(value = "updateSubmit", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updatePost(ModelMap modelMap, User user) {
        userService.update(user);
        return JSONResult.success("修改成功");
    }

    /**
     * 社员密码修改页面跳转
     */
    @RequestMapping("changePassword")
    public String changePassword(HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession().getAttribute(Constants.USER_IN_SESSION);
        modelMap.put("username", user.getName());
        return "user/changePassword";
    }

    /**
     * 密码修改原始密码验证
     */
    @RequestMapping(value = "ajaxPassword", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult ajaxPassword(String password, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constants.USER_IN_SESSION);
        if (password.equals(user.getPassword())) {
            return JSONResult.success("原始密码正确");
        } else {
            return JSONResult.failure("原始密码错误");
        }
    }

    @RequestMapping(value = "changePasswordSubmit", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult changePasswordSubmit(HttpServletRequest request, String realPassword) {
        try {
            User user = (User) request.getSession().getAttribute(Constants.USER_IN_SESSION);
            user.setPassword(realPassword);
            commonService.updateEntity(user);
            return JSONResult.success("密码修改成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JSONResult.failure("密码修改失败");
        }
    }

    /**
     * 用户离职操作
     */
    @RequestMapping("delete")
    @ResponseBody
    public JSONResult delete(@RequestParam Integer id) {
        if (id != null) {
            commonService.deleteEntityById(User.class, id);
        }
        return JSONResult.success("删除成功");
    }

    /**
     * 在职状态恢复
     */
    @RequestMapping("recovery")
    @ResponseBody
    public JSONResult recovery(@RequestParam Integer id) {
        if (id != null) {
            User user = commonService.get(User.class, id);
            user.setStatu(Constants.STATU_FLAG_NORMAL);
            commonService.updateEntity(user);

        }
        return JSONResult.success("删除成功");
    }


    /**
     * 通讯录
     */
    @RequestMapping(value = "contactList", method = RequestMethod.GET)
    public String contactGet(ModelMap modelMap) {
        /**部门列表*/
        List<Depart> departList = commonService.getList(Depart.class);
        FormQuery formQuery = new FormQuery("sys.User", 10, 1);

        ArrayList<FormCriteria> formCriterias = new ArrayList<>();
        formCriterias.add(new FormCriteria("statu", "eq", Constants.STATU_FLAG_NORMAL));

        formQuery.setCriterias(formCriterias);
        Page page = commonService.getPage(formQuery);
        modelMap.addAttribute("departlist", JSON.toJSONString(departList));
        modelMap.addAttribute("page", JSON.toJSONString(page));
        return "user/contactList";
    }

    /**
     * 根据部门获取通讯录
     */
    @RequestMapping(value = "contactList", method = RequestMethod.POST)
    @ResponseBody
    public List<User> contactGetByDepart(String depart) {
        return null;
    }

    @RequestMapping("myinfo")
    public String myinfo(){
        return "user/myinfo";
    }

    @RequestMapping(value = "rebuildPassword",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult rebuildPassword(HttpServletRequest request){
        String no =request.getParameter("no");
        String password =request.getParameter("rebuildPassword");
        if(StringUtil.isNotEmpty(no)&&StringUtil.isNotEmpty(password)){
            User user = commonService.findUniqueByProperty(User.class,"no",no);
            user.setPassword(password);
            commonService.updateEntity(user);
        }else {
            return JSONResult.failure("修改失败");
        }
        return JSONResult.success("修改成功");
    }

}
